package com.mashacoder.volumecontroller;

import com.mashacoder.volumecontroler.R;

import android.app.Service;
import android.content.Context;
import android.media.AudioManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class CardView implements OnSeekBarChangeListener{
	
	private int type;
	private String title;
	private Context context;
	private View card_view;
	private LinearLayout card_layout;
	private SeekBar sb;
	private AudioManager am;
	
	public CardView (int type, String title, int icon, Context context) {
		this.type = type;
		this.title = title;
		this.context = context;
		
		init_card(type, icon);
	}
	
	private void init_card(int type, int icon) {
		LayoutInflater inflater = LayoutInflater.from(context);
		card_view = inflater.inflate(R.layout.card_item, null);
		
		if (icon > 0) {
			ImageView image = (ImageView) card_view.findViewById(R.id.iv_icon);
			image.setBackgroundResource(icon);
		}
		
		TextView tv = (TextView) card_view.findViewById(R.id.tv_title);
		tv.setText(title);
		
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		params.setMargins(0, 0, 0, 10);
		card_layout = (LinearLayout)card_view.findViewById(R.id.card_layout);
		card_layout.setLayoutParams(params);
		
		am = (AudioManager) context.getSystemService(Service.AUDIO_SERVICE);
		int max_volume = am.getStreamMaxVolume(type);
		int now_volume = am.getStreamVolume(type);
		
		sb = (SeekBar) card_view.findViewById(R.id.sb_vol);
		sb.setMax(max_volume);
		sb.setProgress(now_volume);
		sb.setOnSeekBarChangeListener(this);
		
	}
	
	public View get_view() {
		return card_view;
	}
	
	public void refresh_sb() {
		if (sb != null) {
			sb.setProgress(am.getStreamVolume(type));				
		}
	}
	

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		// TODO Auto-generated method stub
		am.setStreamVolume(type, progress, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
		// call back refresh all card
		MainActivity.refresh_card();
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		
	}

}
